package com.ysw.proxy;

import org.springframework.web.client.RestTemplate;

import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * SoaClient的代理对象，用于代理soa请求
 *
 * @author ysw  2019/9/13 9:43 PM
 */
public class SoaClientProxy implements InvocationHandler, Serializable {
    private final RestTemplate restTemplate;
    private Class targetClass;
    private String serviceName;
    private String application;

    public SoaClientProxy(String application, String serviceName, Class beanClass, RestTemplate restTemplate) {
        this.application = application;
        this.serviceName = serviceName;
        this.targetClass = beanClass;
        this.restTemplate = restTemplate;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) {
        // 这里我只是写个示例，这里完全可以通过 服务（service） 来动态获取 请求路径
        String methodName = method.getName();
        Class<?> returnType = method.getReturnType();
        Object forObject = restTemplate.getForObject("http://127.0.0.1:8080/" + methodName, returnType);
        return forObject;
    }

    public Object getProxy() {
        return Proxy.newProxyInstance(targetClass.getClassLoader(), new Class[]{targetClass}, this);
    }
}
